package wxapi

import (
	"bytes"
	"encoding/json"
	"fmt"
	"gitee.com/xmcommon/mlog"
	"net/http"
)

type respCheckimg struct {
	TraceId string `json:"trace_id"`
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

type reqCheckImg struct {
	MediaUrl  string `json:"media_url"`
	MediaType int    `json:"media_type"`
}

func CheckImg(accessToken, mediaUrl string) (expires bool, traceId string, err error) {
	req := reqCheckImg{
		MediaType: 2,
		MediaUrl:  mediaUrl,
	}
	url := fmt.Sprintf("https://api.weixin.qq.com/wxa/media_check_async?access_token=%s", accessToken)
	params, _ := json.Marshal(req)
	request, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(params))
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	res, err := commonPost(request)
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	var r respCheckimg
	err = json.Unmarshal(res, &r)
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	if r.Errcode == 42001 {
		return true, "", nil
	} else if r.Errcode != 0 {
		err = fmt.Errorf(r.Errmsg)
		mlog.Log.Error(err.Error())
		return
	}
	traceId = r.TraceId
	return
}
